<template>
  <el-container>
    <el-header><Header /></el-header>
    <el-main>
      <div class="left">
        <el-card class="box">
          <div class="top">
            <div class="title">{{ article.title }}</div>
            <div class="first-tag-m">
              <el-tag v-for="(tag, i) in tagList" :key="i" size="small">{{ tag }}</el-tag>
            </div>
            <div class="info">
              <span>发布时间：{{ parseTime(article.createTime) }}</span>
              <span>{{ article.likeCount }} 赞</span>
              <span>{{ article.commentCount }} 评论</span>
              <span>{{ article.readCount }} 阅读</span>
            </div>
          </div>
          <div class="articleBox">
            <div class="markdown-body" v-html="article.content" />
          </div>
          <el-divider />
          <div class="likeArticle">
            <div>
              <el-tooltip v-if="userHasCollection === false" class="item" effect="dark" content="收藏" placement="top">
                <el-button circle icon="iconfont icon-shoucang" @click="collection" />
              </el-tooltip>
              <el-tooltip v-else class="item" effect="dark" content="取消收藏" placement="top">
                <el-button circle type="primary" icon="iconfont icon-quxiaoshoucang" @click="cancelCollection" />
              </el-tooltip>
              <el-button v-if="userHasLike === false" circle icon="iconfont icon-dianzan" @click="doLike" />
              <el-button v-else circle type="primary" icon="iconfont icon-dianzan_kuai" @click="doUnLike" />
            </div>
            <div class="report">
              <span @click="addArticleReport">举报</span>
            </div>
          </div>
        </el-card>
        <el-card class="comments">
          <Comment />
        </el-card>
      </div>
      <div class="right">
        <el-card class="authorBox">
          <div class="avatar">
            <router-link :to="{name: 'User', params: { id: article.userId} }">
              <el-avatar :size="80" :src="author.avatar" />
            </router-link>
          </div>
          <div class="author_username">
            <span> {{ author.username }} </span>
          </div>
          <div>
            <span> {{ author.description }} </span>
          </div>
          <div v-if="author.id !== this.$store.state.user.id" class="buttons">
            <el-button v-if="authorIsFocused === false || user_id === ''" @click="focus">关注</el-button>
            <el-button v-else @click="cancelFocus">已关注</el-button>
            <el-button @click="open('/whisper')">私信</el-button>
          </div>
          <div class="authorShow">
            <el-col :span="8">
              <span class="show">文章 </span><span>{{ count.articleCount }}</span>
            </el-col>
            <el-col :span="8">
              <span class="show">问答 </span><span>{{ count.replyCount }}</span>
            </el-col>
            <el-col :span="8">
              <span class="show">获赞 </span><span>{{ count.likeCount }}</span>
            </el-col>
          </div>
        </el-card>
      </div>
    </el-main>
  </el-container>

</template>

<script>
import Header from '../header/index.vue'
import Comment from '../comments/comment.vue'
import { getArticleById, doLike, doUnLike, getArticleLikeCount, isUserLike, collection, cancelCollection, isUserCollected, increaseReadCount } from '@/api/article'
import { findUserById, getReplyLikeCollectCounts, focus, isFocused, cancelFocus } from '@/api/user'
import { addReport } from '@/api/report'
import Swal from 'sweetalert2'
import { mapGetters } from 'vuex'
import { formatTime } from '@/utils/index'
export default {
  components: { Header, Comment },
  data() {
    return {
      article: {
        title: '',
        content: '',
        createTime: '',
        userId: '',
        articleTags: '',
        articleTypeId: '',
        cover: '',
        id: '',
        isDel: ''
      },
      author: {
        id: '',
        username: '',
        avatar: ''
      },
      loading: true,
      tagList: [],
      count: Object(),
      articleLikeCount: '',
      focusOn: '',
      isUserLiked: '',
      isUserCollected: ''
    }
  },
  computed: {
    ...mapGetters([
      'user_id'
    ]),
    authorIsFocused: {
      get() {
        return this.focusOn
      },
      set(v) {
        this.focusOn = v
      }
    },
    likeCount: {
      get() {
        return this.articleLikeCount
      },
      set(v) {
        this.articleLikeCount = v
      }
    },
    userHasLike: {
      get() {
        return this.isUserLiked
      },
      set(v) {
        this.isUserLiked = v
      }
    },
    userHasCollection: {
      get() {
        return this.isUserCollected
      },
      set(v) {
        this.isUserCollected = v
      }
    }
  },
  mounted() {
    this.increReadCount()
    this.articleDetail() // 需要该方法先执行完毕才能获取到后面方法参数的articleId,或者可以从this.$route.params.id中拿id
    this.getLikeCount()
    setTimeout(() => {
      this.isFocus() // 需要this.articleDetail()中拿到author.id
      this.isUserLike()
      this.isUserCollect()
      this.getReplyLikeCollectCounts()
    }, 100)
    this.loading = false
  },
  methods: {
    parseTime(time) {
      return formatTime(new Date(time))
    },
    articleDetail() {
      getArticleById({ articleId: this.$route.params.id }).then(res => {
        this.article = res.data
        console.log(1)
        console.log(this.article)
        if (this.article.articleTags !== null) {
          if (this.article.articleTags.indexOf(',') !== -1) {
            this.tagList = this.article.articleTags.split(',')
          } else {
            this.tagList.push(this.article.articleTags)
          }
        }
        console.log(this.tagList)
        findUserById({ id: this.article.userId }).then(response => {
          this.author.avatar = response.data.avatar
          this.author.id = response.data.id
          this.author.username = response.data.username
        })
      })
    },
    getReplyLikeCollectCounts() {
      getReplyLikeCollectCounts({ userId: this.article.userId }).then(res => {
        this.count = res.data
      })
    },
    editMarkdown(id) {
      this.$router.push('/editArticle/' + id)
    },
    focus() {
      if (this.$store.state.user.id === '') {
        this.$message({
          type: 'warning',
          message: '请先登录'
        })
        return
      }
      focus({ userId: this.$store.state.user.id, authorId: this.author.id }).then(res => {
        if (res.code === 1) {
          this.$message({
            message: '关注成功',
            type: 'success'
          })
          this.authorIsFocused = res.data
        }
      })
    },
    cancelFocus() {
      cancelFocus({ userId: this.$store.state.user.id, authorId: this.author.id }).then(res => {
        if (res.code === 1) {
          this.$message({
            message: '取消关注成功',
            type: 'success'
          })
        }
        this.authorIsFocused = res.data
      })
    },
    // 是否关注作者
    isFocus() {
      const authorId = this.author.id
      isFocused({ userId: this.$store.state.user.id, authorId: authorId }).then(res => {
        this.focusOn = res.data
      })
    },
    getLikeCount() {
      getArticleLikeCount({ articleId: this.$route.params.id }).then(res => {
        this.articleLikeCount = res.data
      })
    },
    doLike() {
      doLike({ userId: this.$store.state.user.id, articleId: this.article.id }).then(res => {
        if (res.code === 1) {
          this.$message({
            message: '点赞成功',
            type: 'success'
          })
          this.isUserLike()
          this.getLikeCount()
        }
      })
    },
    doUnLike() {
      doUnLike({ userId: this.$store.state.user.id, articleId: this.article.id }).then(res => {
        if (res.code === 1) {
          this.$message({
            message: '取消点赞成功',
            type: 'success'
          })
          this.isUserLike()
          this.getLikeCount()
        }
      })
    },
    // 是否给文章点赞
    isUserLike() {
      isUserLike({ userId: this.$store.state.user.id, articleId: this.article.id }).then(res => {
        this.isUserLiked = res.data
      })
    },
    collection() {
      collection({ userId: this.$store.state.user.id, articleId: this.$route.params.id }).then(res => {
        this.isUserCollected = true
      })
    },
    cancelCollection() {
      cancelCollection({ userId: this.$store.state.user.id, articleId: this.$route.params.id }).then(res => {
        this.isUserCollected = false
      })
    },
    isUserCollect() {
      isUserCollected({ userId: this.$store.state.user.id, articleId: this.$route.params.id }).then(res => {
        this.isUserCollected = res.data
      })
    },
    increReadCount() {
      increaseReadCount({ articleId: this.$route.params.id })
    },
    addArticleReport() {
      Swal.fire({
        title: '确定要举报吗?',
        icon: 'question',
        confirmButtonText: '确定',
        showCancelButton: true,
        cancelButtonText: '取消',
        heightAuto: false
      }).then(res => {
        if (res.isConfirmed) {
          addReport({ userId: this.$store.state.user_id, itemId: this.$route.params.id,
            reportType: 0 }).then(res => {
            if (res.code === 1) {
              Swal.fire('举报成功!', '', 'success')
            }
          })
        }
      })
    },
    open(url) {
      if (!this.$store.getters.user_id) {
        Swal.fire({
          title: '请先登录',
          icon: 'warning',
          confirmButtonText: 'OK',
          heightAuto: false
        })
        return
      }
      localStorage.setItem('toUserId', this.author.id)
      localStorage.setItem('name', this.author.username)
      this.$router.push('/whisper/myChats')
    }
  }
}
</script>

<style lang="scss" scoped>
 .el-container {
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    min-height: 100%;
  }
  .el-header {
    padding:0;
    margin:0;
  }
  .el-main {
    // overflow: auto;
    background-color: #f3f4f5; /*#e9e7ef*/
    display: flex;
    justify-content: center;
  }
  .el-footer{
    padding:0;
  }
.left{
  width:888px;
}
.title {
    margin-top: 20px;
    font-family: PingFangSC-Medium;
    font-size: 22px;
    color: #333;
    font-weight: 700;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
}
.first-tag-m {
    margin-top: 20px;
}
.info {
    margin-top: 20px;
}
.info span:first-child {
    margin-left: 0;
}
.info span {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #999;
    margin-left: 31px;
}
.articleBox{
  padding: 0 120px;
  margin-top: 20px;
}
.authorBox{
  margin-left: 20px;
  width: 500px;
}
.avatar {
  display: block;
  text-align: center;
  .el-avatar{
    float: none;
  }
}
.author_username{
  display: block;
  text-align: center;
  margin: 10px 0 20px 0;
  font-size: 20px;
  font-weight: 700;
  font-family: PingFangSC-Medium;
  line-height: 20px;
}
.buttons{
  display: block;
  padding-left: 150px;
}
.authorShow{
  display: block;
  height: 30px;
  color: #4b5cc4;
  font-family: PingFangSC-Medium;
  font-size: 15px;
  font-weight: 700;
  text-align: center;
  margin-top: 20px;
}
.comments{
  width: 888px;
  margin-top: 20px;
}
.likeArticle{
  display: flex;
  justify-content: center;
}
.report{
  color: #9999b3;
  font-size: 14px;
  cursor: pointer;
  margin-left: 100px;
  padding-top: 10px;
}
.markdown-body{
  font-size: 16px;
  font-family: 'Pingfang SC';
  line-height:1.8 ;
  word-break: break-all;
}
.markdown-body ::v-deep img {
    display: block;
    max-width: 90%;
    margin: 0 auto;
}
.el-card__header{
  padding: 18px 0;
}
.top {
  padding: 0 30px;
  padding-top: 40px;
}

</style>
